package com.neteast.androidclient.contact.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;
/**
 * 异步下载任务，下载新版本的apk，并自动安装，在提示栏更新下载进度
 * @author tiangh
 * 2012-4-5 下午3:18:33
 */
public class DownloadTask extends  AsyncTask<Void, Integer, Void> {
	
	private NotificationHelper mNotificationHelper;

    SharedPreferences settings;
    SharedPreferences.Editor editor;
    Context context;
    public DownloadTask(Context context){
        this.context = context;
        mNotificationHelper = new NotificationHelper(context);
    }

	@Override
	protected Void doInBackground(Void... params) {
		 try {
				float oldVersion = LoginUtil.getVersion(context);
				String path=LoginUtil.getBaseUrl(context)+"/Usercenter/download?version="+oldVersion;
				URL url=new URL(path);
				HttpURLConnection conn=(HttpURLConnection) url.openConnection();
				conn.setRequestMethod("GET");
				path = new String(JsonUtil.getDataFromInputStream(conn.getInputStream()));
				Log.i("test", "path="+path);
				conn.disconnect();
//				if (path.trim().equals("false")) {
//					return;
//				}
				if (path.startsWith("http://")) {
					url=new URL(path);
					String dir = FileUtil.createDir(context);
					File file=new File(dir, url.getFile());
					file.getParentFile().mkdirs();
					file.createNewFile();
					conn=(HttpURLConnection) url.openConnection();
					conn.setRequestMethod("GET");
					FileOutputStream fos=new FileOutputStream(file);
					InputStream ins = conn.getInputStream();
					int lenghtOfFile = conn.getContentLength();
					long total = 0;
					int len=0;
					byte[] buffer=new byte[1024];
					while((len=ins.read(buffer))>0)
					{
						total += len;
		                Log.d("%Percentage%",""+(int)((total*100)/lenghtOfFile));
		                onProgressUpdate((int)((total*100)/lenghtOfFile));
		                fos.write(buffer, 0, len);
					}
					ins.close();
					fos.close();
					Intent intent = new Intent();    
					// 设置目标应用安装包路径    
					intent.setDataAndType(Uri.fromFile(file),"application/vnd.android.package-archive");
					intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					context.startActivity(intent);
				}
	        }catch (Exception e) {}
	        return null;
	}
	
    protected void onPreExecute(){
        mNotificationHelper.createNotification();
    }

    protected void onProgressUpdate(Integer... progress) {
        mNotificationHelper.progressUpdate(progress[0]);
    }
    protected void onPostExecute(Void result)    {
        mNotificationHelper.completed();
    }
    
    public class NotificationHelper {
        private Context mContext;
        private int NOTIFICATION_ID = 1;
        private Notification mNotification;
        private NotificationManager mNotificationManager;
        private PendingIntent mContentIntent;
        private CharSequence mContentTitle;
        public NotificationHelper(Context context)
        {
            mContext = context;
        }

        public void createNotification() {
            mNotificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);

            int icon = android.R.drawable.stat_sys_download;
            CharSequence tickerText = "下载中";
            long when = System.currentTimeMillis();
            mNotification = new Notification(icon, tickerText, when);

            mContentTitle =  "下载中";
            CharSequence contentText = "完成 0%"; 

            Intent notificationIntent = new Intent();
            mContentIntent = PendingIntent.getActivity(mContext, 0, notificationIntent, 0);

            mNotification.setLatestEventInfo(mContext, mContentTitle, contentText, mContentIntent);

            mNotification.flags = Notification.FLAG_ONGOING_EVENT;

            mNotificationManager.notify(NOTIFICATION_ID, mNotification);
        }

        public void progressUpdate(int percentageComplete) {
            CharSequence contentText = "完成 "+percentageComplete+"%";
            mNotification.setLatestEventInfo(mContext, mContentTitle, contentText, mContentIntent);
            mNotificationManager.notify(NOTIFICATION_ID, mNotification);
        }

        public void completed()    {
            mNotificationManager.cancel(NOTIFICATION_ID);
        }
    }
}
